<?php
namespace app\common\model;

require("/www/wwwroot/nft_w/vendor/phpmailer/phpmailer/src/PHPMailer.php");
require("/www/wwwroot/nft_w/vendor/phpmailer/phpmailer/src/SMTP.php");
require("/www/wwwroot/nft_w/vendor/phpmailer/phpmailer/src/Exception.php");

use think\facade\Log;
use think\Model;
use think\Cache;

class SmsModel extends Model{

    /**
     * 密码加密
     * $userid：用户账号
     * $pwd：用户密码
     */
    public function encrypt_pwd($userid, $pwd)
    {
		$char = '00000000';//固定字符串
		$time = date('mdHis', time());//时间戳
		$pwd = md5($userid . $char . $pwd . $time);//拼接字符串进行加密
		return array('pwd' => $pwd, 'time' => $time);
    }


    /**
     * 短信内容加密
     * $content：短信内容
     */
    public function encrypt_content($content)
    {
       return urlencode(iconv('UTF-8', 'GBK', $content));//短信内容转化为GBK格式再进行urlencode格式加密
    }


    /**
     * 短连接请求方法
     * $url：请求地址
     * $post_data：请求数据
     */
    private function connection($url,$post_data){
		$attributes = array('Accept:text/plain;charset=utf-8', 'Content-Type:application/json', 'charset=utf-8', 'Expect:', 'Connection: Close');//请求属性
		$ch = curl_init();//初始化一个会话
		/* 设置验证方式 */
		curl_setopt($ch, CURLOPT_HTTPHEADER, $attributes);//设置访问
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);//设置返回结果为流
		curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5);//设置请求超时时间
		curl_setopt($ch, CURLOPT_TIMEOUT, 60);//设置响应超时时间
		/* 设置通信方式 */
		curl_setopt($ch, CURLOPT_POST, 1);
		curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
		curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
		curl_setopt($ch, CURLOPT_URL, $url);
		curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);//使用urlencode格式请求

		$result = curl_exec($ch);//获取返回结果集
		$result=preg_replace('/\"msgid":(\d{1,})./', '"msgid":"\\1",', $result);//正则表达式匹配所有msgid转化为字符串
		$result = json_decode($result, true);//将返回结果集json格式解析转化为数组格式
		if (curl_errno($ch) !== 0) //网络问题请求失败
		{
			$result['result'] = '310099';
			curl_close($ch);//关闭请求会话
			return $result;
		} else {
			$statusCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
			if ($statusCode != 200||!isset($result['result']))//域名问题请求失败或不存在返回结果
			{
				$result='';//清空result集合
				$result['result'] = '310099';
			}
			curl_close($ch);//关闭请求会话
			return $result;
		}
    }


    /*
    * 单条发送
     * $data:请求数据集合
    */
    public function singleSend($data){
		$data['userid']	= strtoupper($data['userid']);//用户名转化为大写
		$encrypt		= $this->encrypt_pwd($data['userid'],$data['pwd']);//密码进行MD5加密
		$data['pwd']	= $encrypt['pwd'];//获取MD5加密后的密码
		$data['timestamp']	= $encrypt['time'];//获取加密时间戳
		$data['content']	= $this->encrypt_content($data['content']);//短信内容进行urlencode加密
		$post_data		= json_encode($data);//将数组转化为JSON格式
		$result			= $this->connection($data['BaseUrl'].'single_send',$post_data);//根据请求类型进行请求
		return $result;//返回请求结果
    }


    /*
   * 相同内容群发
    * $data:请求数据集合
   */
    public function batchSend($data){
		$data['userid']	= strtoupper($data['userid']);//用户名转化为大写
		$encrypt		= $this->encrypt_pwd($data['userid'],$data['pwd']);//密码进行MD5加密
		$data['pwd']	= $encrypt['pwd'];//获取MD5加密后的密码
		$data['timestamp']	= $encrypt['time'];//获取加密时间戳
		$data['content']	= $this->encrypt_content($data['content']);//短信内容进行urlencode加密
		$post_data		= json_encode($data);//将数组转化为JSON格式
		$result			= $this->connection($data['BaseUrl'].'batch_send',$post_data);//根据请求类型进行请求
		return $result;
    }


    /*
    * 个性化内容群发
     * $data:请求数据集合
    */
    public function multiSend($data){
            $data['userid']	= strtoupper($data['userid']);	//用户名转化为大写
			$encrypt		= $this->encrypt_pwd($data['userid'],$data['pwd']);	//密码进行MD5加密
			$data['pwd']	= $encrypt['pwd'];		//获取MD5加密后的密码
			$data['timestamp']	= $encrypt['time'];	//获取加密时间戳
            foreach($data['multimt'] as $k=>$v){
                $data['multimt'][$k]['content']	= $this->encrypt_content($v['content']);//每一条个性化的短信内容进行urlencode加密
            }
            $post_data	= json_encode($data);//将数组转化为JSON格式
            $result		= $this->connection($data['BaseUrl'].'multi_send',$post_data);//根据请求类型进行请求
            return $result;
    }


    /*
   * 查询余额
    * $data:请求数据集合
   */
    public function getBalance($data){
		$data['userid']	= strtoupper($data['userid']);//用户名转化为大写
		$encrypt		= $this->encrypt_pwd($data['userid'],$data['pwd']);//密码进行MD5加密
		$data['pwd']	= $encrypt['pwd'];//获取MD5加密后的密码
		$data['timestamp']	= $encrypt['time'];//获取加密时间戳
		$post_data		= json_encode($data);//将数组转化为JSON格式
		$result			= $this->connection($data['BaseUrl'].'get_balance',$post_data);//根据请求类型进行请求
		return $result;
    }


    /*
     * 请求获取上行
     * $requestPath:请求地址
     * $data:请求数据集合
     * $isEncryptPwd:是否加密
    */
    public function getMo($data){
		$data['userid']	= strtoupper($data['userid']);//用户名转化为大写
		$encrypt		= $this->encrypt_pwd($data['userid'],$data['pwd']);//密码进行MD5加密
		$data['pwd']	= $encrypt['pwd'];//获取MD5加密后的密码
		$data['timestamp']	= $encrypt['time'];//获取加密时间戳
		$post_data		= json_encode($data);//将数组转化为JSON格式
		$result			= $this->connection($data['BaseUrl'].'get_mo',$post_data);//根据请求类型进行请求
		return $result;//返回请求结果
    }


    /*
	  * 请求获取状态报告
	  * $requestPath:请求地址
	  * $data:请求数据集合
	  * $isEncryptPwd:是否加密
	 */
    public function getRpt($data)
    {
		$data['userid']=strtoupper($data['userid']);//用户名转化为大写
		$encrypt=$this->encrypt_pwd($data['userid'],$data['pwd']);//密码进行MD5加密
		$data['pwd']=$encrypt['pwd'];//获取MD5加密后的密码
		$data['timestamp']=$encrypt['time'];//获取加密时间戳
		$post_data = json_encode($data);//将数组转化为JSON格式
		$result=$this->connection($data['BaseUrl'].'get_rpt',$post_data);//根据请求类型进行请求
		return $result;
    }

    protected function send_nxsms($dest,$phone,$code){
        $data = array();

        $config = [
            'url'                 =>'http://api2.nxcloud.com/api/sms/mtsend',
            'appkey'              =>'aqmG7Uew',
            'secretkey'           =>'*nB2Jp8*',
        ];

        Log::write("sms send:".$dest.$phone);

        $data['BaseUrl']	=	$config["url"];
        $data['appkey']	=	$config["appkey"];
        $data['secretkey']	=	$config["secretkey"];
        $data['content']	=	urlencode('Your sms code is: '.strval($code).' , please ignore if this not your operation');
        $data['phone']	=	"00".strval($dest).strval($phone)	;
//        $data['variables_values']	=	$code;

        $headers = array(
//            'authorization:'.$data['authorization']
        );
        $result	= $this->conn2($data['BaseUrl'],$data,$headers);//根据请求类型进行请求

        // print_r($data);
        // print_r($result);
        // Array
        //     (
        //         [result] => 请求成功
        //         [code] => 0
        //         [messageid] => fc9da9c6c5314a23a53d6a014136470b
        //     )
//        Log::write("sms ret data:".json_encode($result));
        if (isset($result["code"])&&$result["code"]=="0"){
            $result['result'] = 0;
        }else{
            $result['result'] = 1;
        }
        return $result;//返回请求结果
    }

    public function send($dest,$phone,$code){
        return $this->send_nxsms($dest,$phone,$code);
    }
    public function sendCode2Mail($targetmail){
//        $targetmail = (input('post.mail')) ? input('post.mail') : '';// 邮箱
        $title = "Verified code";
        $code = rand(100000,999999);
        $content = "Your verify code is :".$code;

        $code_rand		= (input('post.code_rand')) ? input('post.code_rand') : '';// 随机码
//        $code			= (input('post.code')) ? input('post.code') : '';// 验证码

        cache('C_Code_'.$code_rand, NULL);

        Log::write("aaaaaa".$targetmail);
        $ret = $this->sendMail2($targetmail,$code);
        Log::write("bbbbb".json_encode($ret));
        $data = array(
            "code"=>0
        );
        $homelog = array(
            'uid'		=>	0,
            'time'		=>	time(),
            'params'	=>	'邮件注册名：'.$targetmail,
            'values'	=>	'验证码:'.strval($code),
            'ip'		=>	'',
            'func'		=>	'register 发送成功',
            'cla'		=>	'user register'
        );
        if(strval($ret)=="1"){// 发送邮件
            cache('C_Code_'.$targetmail, $code, 1800);
            $cachesmscode = cache('C_Code_'.$targetmail);
            $homelog['values'] .= ",cache 保存:".strval($cachesmscode);
            $data['code'] = 1;
        }else{
            $homelog['func'] = '注册环境发送失败：'.$ret;
            $data['code_dec'] = "Mailer Error: ".$ret;
        }
        model('Homelog')->insert($homelog);
        return json($data);
    }

    public function sendMail($targetmail,$code){
        $url = "http://api2.nxcloud.com/api/email/otp";
        $post_data = array(
            "appKey"=>"k9dNv5YN","secretKey"=>"fhixlBGu",
            "from"=>"services@168nba.com",
            "to"=>$targetmail,"templateName"=>"168nba",
            "templateData"=>array("vCode"=>$code),
        );
        $ret = $this->conn3($url,$post_data);
        if ($ret['code']==0){
            return "1";
        }
        return $ret['msg'];
    }

    public function sendMail2($targetmail,$code){
//        $targetmail = '1@11.com';

        //端口25或者587
        $config = array(
            "host"=>"server64.web-hosting.com","port"=>465,
            "mail"=>'emailcenter@spackero.com',
            "password"=>"1bS5wbC#9jYS5jcm",
//            "secure"=>"STARTTLS"   //outlook365
            "secure"=>"ssl"
        );

        $title = "Verified code";
        $content = 'Your code is: '.strval($code).' , please ignore if this not your operation';


        $mail = new \PHPMailer\PHPMailer\PHPMailer();

        $mail->isSMTP();// 使用SMTP服务
        $mail->CharSet = "utf8";// 编码格式为utf8，不设置编码的话，中文会出现乱码
        $mail->Host = $config['host'];// 发送方的SMTP服务器地址
        $mail->SMTPAuth = true;// 是否使用身份验证
        $mail->Username = $config['mail'];
        $mail->Password = $config['password'];
        $mail->SMTPSecure = $config['secure'];
        $mail->Port = $config['port'];
        $mail->setFrom($config['mail'],"Mailer");// 设置发件人信息，如邮件格式说明中的发件人，这里会显示为Mailer(xxxx@163.com），Mailer是当做名字显示
        $mail->addAddress($targetmail);// 设置收件人信息，如邮件格式说明中的收件人，这里会显示为Liang(yyyy@163.com)
        $mail->addReplyTo($config['mail']);
        $mail->Subject = $title;// 邮件标题
        $mail->Body = $content;// 邮件正文
        //$mail->AltBody = "This is the plain text纯文本";// 这个是设置纯文本方式显示的正文内容，如果不支持Html方式，就会用到这个，基本无用

        if(!$mail->send()){// 发送邮件
            $errorMsg = "mail send busy,try later please";
//            return $errorMsg;
            return $mail->ErrorInfo;
        }else{
            return 1;
        }
    }

	public function sendSMSCode($dest,$phone=''){

		if (!$phone) return ['code'=>0,'code_dec'=>'Please input phone '];

        $phone = str_replace("+","",$phone);

        $ip = request()->ip();

        if(!$ip){
            return ['code'=>0, 'code_dec'=>'Fail'];
        }

        $code = rand(100000,999999);
        $sastime = date('Y-m-d H:i:s');
        file_put_contents('ip.txt', $ip.'-----'.$phone.'--------'.$sastime.PHP_EOL,FILE_APPEND);
        //时间段判定
        $TwoOclock = mktime(2,30,0,date('m'),date('d'),date('Y'));
        $FiveOclock = mktime(5,30,0,date('m'),date('d'),date('Y'));
        //if(time()>$TwoOclock && time()<$FiveOclock) return ['code'=>0,'code_dec'=>'发送频繁，稍后再试t'];

        $sendtime = cache('C_sendtime_'.$ip) ? cache('C_sendtime_'.$ip) : time()-3600*3;
        if(time()-$sendtime < 3600*3){
            //return ['code'=>0,'code_dec'=>'发送频繁，稍后再试i'];
        }
        cache('C_sendtime_'.$ip,time()+3600*3);


//        $is_sms	=	model('Setting')->where('id',1)->value('is_sms');
//
//        if($is_sms==2){
//            return ['code'=>0, 'code_dec'=>'失败'];
//        }

//		$mobile = '00'.$dest.$phone;
        $mobile = $dest.$phone;
        /**
         * 发送间隔时间
         */
        if (!is_null(cache('interval'.$mobile)) && time() - cache('interval'.$mobile) < 5) return ['code'=>0, 'code_dec'=>'The sending frequency is too fast'];
        cache('interval'.$mobile, time());

        //短信发送
        $result = $this->send($dest,$phone,$code);

        $homelog = array(
            'uid'		=>	0,
            'time'		=>	time(),
            'params'	=>	'手机号：'.$mobile,
            'values'	=>	'验证码:'.strval($code),
            'ip'		=>	'',
            'func'		=>	'register 验证码发送成功',
            'cla'		=>	'user register'
        );
        if ($result['result'] === 0) {
            //生成验证码的缓存
            cache('C_Code_'.$phone, $code, 1800);
            $cachesmscode = cache('C_Code_' . $phone);
            $homelog['values'] .= ",cache 保存:".strval($cachesmscode);
            model('Homelog')->insert($homelog);
            return ['code'=>1, 'code_dec'=>'The certificate code has been sent, please check it!'];
        }else if ($result['result'] === 1){
            $homelog['func'] = '发送失败,通道返回:'.json_encode($result);
            model('Homelog')->insert($homelog);
            return ['code'=>0, 'code_dec'=>'The phone number is invalid, please try again!'];
        }else{
            $homelog['func'] = '手机验证码无法发送';
            model('Homelog')->insert($homelog);
            return ['code'=>0, 'code_dec'=>'Failed to send the verification code, please try again!'];
        }
	}

    private function conn2($url,$post_data){
        $postData = http_build_query($post_data);
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_USERAGENT,'Opera/9.80 (Windows NT 6.2; Win64; x64) Presto/2.12.388 Version/12.15');
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false); // stop verifying certificate
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($curl, CURLOPT_POST, true);
        curl_setopt($curl, CURLOPT_HTTPHEADER, array('Content-Type: application/x-www-form-urlencoded'));
        curl_setopt($curl, CURLOPT_POSTFIELDS, $postData);
        curl_setopt($curl, CURLOPT_FOLLOWLOCATION, true);
        $result = curl_exec($curl);
        curl_close($curl);
        return $result = json_decode($result, true);;
    }

}
